<template>
	<view>
		<view class="btn1">
			<button @click="open">筛选</button>
			<button @click="reset">重置</button>
		</view>
		<u-collapse ref="collapse" :accordion="true" @change="change">
			<u-collapse-item :title="pro.proId" :value="''+pro.proPrice" v-for="(pro,listIndex) in list"
				:key="listIndex" style="font-weight:bold;background-color: #fff;">
				<view v-if="pro.proColor">
					<scroll-view scroll-x style="width:100%" class="navscroll">
						<table style="border-color: #999;margin-top: 10rpx;border-collapse:collapse;" cellspacing="0"
							border="0">
							<!-- <view>{{item.proColor}}</view> -->
							<colorItem @tdClick="tdClick(pro,$event)" :color="color" :pro="pro" :sizes="pro.proSize"
								v-for="(color, colorindex) in pro.proColor" :key="colorindex">
							</colorItem>
							<!-- <tr v-for="(color, colorindex) in pro.proColor" :key="colorindex">
								<td>{{color}}</td>
								<td @click.stop="tdClick(pro,{size,color})" v-for="(size,sizeindex) in pro.proSize"
									:key="sizeindex">
									<span style="font-size:16px;">{{size}}</span>
									<u-icon
										v-if="pro.proConfig.findIndex(item=>item.color==color&&item.size == size)>=0"
										name="checkmark" size=46 class="icon-class"
										style="font-size:36px;position: absolute;right: 0;bottom: 0;" color="red">
									</u-icon>
								</td>
							</tr> -->

						</table>
					</scroll-view>
					<u-button :custom-style="button" @click="openModal(listIndex)" class="button" type="primary"
						color="red" text="确定">
					</u-button>
				</view>
				<view v-else>
					<u-divider textSize="34" text="暂无数据"></u-divider>
				</view>
			</u-collapse-item>
		</u-collapse>
		<u-popup :show="show" closeOnClickOverlay mode="center" @close="close">
			<scroll-view scroll-y style="height:400px" class="navscroll">
				<view style="padding: 20rpx;width: 80vw; font-size: 32rpx;">
					<view v-for="(item,index) in lableList"
						style="display: flex;border: 1rpx #999 solid;justify-content: center;align-items: stretch; ">
						<view style="padding:20rpx; 30rpx;flex: 1;white-space:normal; word-break:break-all;">
							{{item.proId}}{{item.color}}{{item.size}}
						</view>
						<view
							style="padding:20rpx; 30rpx;  border-left: 1rpx #999 solid;display: flex;justify-content: center;align-items: center;">
							<input placeholder="1" placeholder-class="placeholder_class" v-model="item.number"
								style="width: 100rpx;" type="digit" />
						</view>
					</view>
					<u-button @click="submit" :custom-style="button" type="primary" color="red" text="确定"></u-button>
				</view>
			</scroll-view>
		</u-popup>
		<u-popup :show="show1" closeOnClickOverlay mode="bottom" :round="20" @close="show1 = false" @open="open">
			<view class="toast">
				<view class="form">
					<view class="select">
						<view class="text"> <text>*</text>货号: </view>
						<view style="display: flex;align-items: center;" class="">
							<input v-model="formData.proId" type="text" placeholder="请输入货号" />
							<view @tap="open2" class="seacchBtn">
								选择
							</view>
						</view>
					</view>
					<!--
					<view class="select">
						<view class="text"> <text>*</text>颜色: </view>
						<input v-model="proColor" type="text" placeholder="请输入颜色" />
					</view> -->
					<!-- view class="select">
						<view class="text"> <text>*</text>尺码: </view>
						<input v-model="proSize" type="text" placeholder="请输入尺码" />
					</view> -->
				</view>
				<view class="btn">
					<button @tap="search">查询</button>
				</view>
			</view>
		</u-popup>
		<Prop @close="close2" ref="child" @saveUser="saveUser" />
	</view>
</template>

<script>
	// #ifndef MP-WEIXIN
	var tsc = require("../../util/ble/tsc.js");
	var esc = require("../../util/ble/esc.js");
	var encode = require("../../util/ble/encoding.js");
	// #endif
	import colorItem from "./colorItem.vue"
	var app = getApp()
	import Prop from "../../components/prop.vue"
	export default {
		components: {
			Prop,
			colorItem
		},
		data() {
			return {
				button: {
					width: '100rpx',
					height: '60rpx',
					margin: 0,
					float: 'right',
					marginTop: '20rpx'
				},
				show1: false,
				focus: true,
				show: false,
				formData: {
					pageNo: 1,
					pageSize: 50,
					proId: "",
					stt: "0"
				},
				list: [],
				lableList: [],
				//
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				proId: ""
			};
		},
		onReachBottom() {
			this.formData.pageNo++
			this.getList(this.formData)
		},
		methods: {

			reset() {
				this.formData.proId = ''
				this.search("0")
			},
			async search(stt) {
				this.formData.pageNo = 1
				this.formData.stt = stt
				await this.getList(this.formData);
				this.show = false;
			},
			close2() {
				this.focus = false
				this.$nextTick(() => {
					this.focus = true
				})
			},
			saveUser(data) {
				this.formData.proId = data.proId;
				this.$refs.child.close();
			},
			open2() {
				this.$refs.child.open();
				// console.log(this.$refs.input.focus())
				// this.focus = true
				// console.log(this.focus)
			},
			submit() {
				let that = this
				uni.getConnectedBluetoothDevices({
					success(res) {
						console.log(res)
						if (res.devices.length == 0) {
							uni.navigateTo({
								url: "/pages/setup/Bluetooth",
							});
							return
						} else {
							let contentFlag = uni.getStorageSync('contentFlag')
							if (contentFlag == 2) {
								uni.showModal({
									content: '当前默认打印参数为票据打印，是否前往设置？',
									success: function(res) {
										if (res.confirm) {
											// console.log('用户点击确定');
											uni.navigateTo({
												url: "/pages/setup/Bluetooth"
											})
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
								return
							}
							var deviceId = uni.getStorageSync('deviceId');
							if (deviceId == "") {
								uni.navigateTo({
									url: "/pages/setup/Bluetooth",
								});
								return
							}
							// console.log(this.lableList)
							let params = that.lableList.map(item => ({
								proNum: (item.number == null) ? 1 : item.number,
								proSku: item.proSku,
								proId: item.proId,
								proColor: item.color,
								remark: item.remark,
								proSize: item.size
							}))
							that.$api.getPrintSeqtApi({
								proSkus: params
							}).then(res => {
								// console.log(res)
								that.labelTest(res.result.lists)
							})
						}
					}
				})

			},
			openModal(index) {

				if (this.list[index].proConfig.length == 0) {
					uni.showToast({
						title: "请选择尺码",
						icon: "none"
					})
					return
				}

				this.lableList = this.list[index].proConfig
				this.show = true
			},
			async getList(formData) {
				this.$nextTick(() => {
					this.$refs.collapse.init()
				})
				if (formData.proId === '') {
					this.formData.stt = '0';
				} else {
					this.formData.stt = '';
				}
				let requestData = uni.$u.deepClone(formData);
				Object.keys(requestData).map((item) => {
					if (requestData[item] == '' || requestData[item] == null) {
						delete requestData[item]
					}
				});
				let data = await this.$api.productListApi({
					data: requestData
				})
				if (data.code == 200) {
					for (let item of data.result.list) {
						item.proConfig = []
						item.proColor = item.proColor && item.proColor.split(",") || ""
						item.proSize = item.proSize && item.proSize.split(",") || ""
					}
					this.show1 = false
					this.list = requestData.pageNo == 1 ? data.result.list : this.list.concat(data.result.list)
					console.log(this.list);
					if (data.result.list <= 0 && this.list.length > 0) {
						// uni.showToast({
						// 	title: "没有更多了",
						// 	icon: "none"
						// })
					}
				}
			},
			tdClick(item, {
				size,
				color
			}) {
				// console.log(item, size, color);
				let index = item.proConfig.findIndex(item => {
					return item.size == size && item.color == color
				})
				if (index >= 0) {
					item.proConfig.splice(index, 1)
				} else {
					item.proConfig.push({
						size,
						color,
						proId: item.proId,
						remark: item.remark || '',
						proSku: item.proSku,
						number: null
					})
				}

			},

			open(e) {
				// console.log('open', e)
				this.show1 = true
			},
			close(e) {
				// console.log('close', e)
				this.show = false
			},
			change(e) {
				// console.log('change', e)
			},

			//标签打印
			labelTest(list) {
				// 第一行字体大小
				let firstSize = JSON.parse(uni.getStorageSync('printConfig'))[0].value
				// 宽
				let width = JSON.parse(uni.getStorageSync('printConfig'))[2].value
				// 高
				let height = JSON.parse(uni.getStorageSync('printConfig'))[3].value
				// 第三行字体大小
				let lastSize = JSON.parse(uni.getStorageSync('printConfig'))[6].value
				// 单双
				let column = JSON.parse(uni.getStorageSync('printConfig'))[7].value
				// return
				console.log(firstSize, width, height, lastSize, column)
				if(width!=40||width!=50||width!=60||width!=80||width!=100){
					// uni.showModal({
					// 	content: '当前尺寸不符合标准，请前往后台设置尺寸！',
					// 	success: function(res) {
					// 		if (res.confirm) {
					// 			console.log('用户点击确定');
					// 		} else if (res.cancel) {
					// 			console.log('用户点击取消');
					// 		}
					// 	}
					// });
					// return
					width=50
				}
				// #ifndef MP-WEIXIN
				if (column == 2) {
					if (width == 50) {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(50 * 2, 30)
						let x = 0;
						let y = 0;
						let index = 0
						while (index < list.length) {
							let that = this;
							command.setGap(5)
							command.setCls()
							command.setText(60, y + 30, "TSS24.BF2", 2, 2,
								`${list[index].proId}${list[index].proColor}${list[index].proSize}`)
							command.setBarCode(60, y + 100, "128", 64, 1, 2, 2, `${list[index].labelNo}`)
							command.setText(150, y + 200, "TSS24.BF2", 1, 1,
								`${list[index].remark!=null?list[index].remark:''}`)
							index++
							if (index < list.length) {
								command.setText(470, y + 30, "TSS24.BF2", 2, 2,
									`${list[index].proId}${list[index].proColor}${list[index].proSize}`)
								command.setBarCode(480, y + 100, "128", 56, 1, 2, 2, `${list[index].labelNo}`)
								command.setText(600, y + 200, "TSS24.BF2", 1, 1,
									`${list[index].remark!=null?list[index].remark:''}`)
							}
							command.setPagePrint()
							that.prepareSend(command.getData())
							index++
						}
					} else {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(50 * 2, 30)
						let x = 0;
						let y = 0;
						let index = 0
						while (index < list.length) {
							let that = this;
							command.setGap(5)
							command.setCls()
							command.setText(70, y + 30, "TSS24.BF2", 2, 2,
								`${list[index].proId}${list[index].proColor}${list[index].proSize}`)
							command.setBarCode(80, y + 85, "128", 80, 1, 2, 2, `${list[index].labelNo}`)
							command.setText(150, y + 200, "TSS24.BF2", 1, 1,
								`${list[index].remark!=null?list[index].remark:''}`)
							index++
							if (index < list.length) {
								command.setText(420, y + 30, "TSS24.BF2", 2, 2,
									`${list[index].proId}${list[index].proColor}${list[index].proSize}`)
								command.setBarCode(420, y + 85, "128", 80, 1, 2, 2, `${list[index].labelNo}`)
								command.setText(500, y + 200, "TSS24.BF2", 1, 1,
									`${list[index].remark!=null?list[index].remark:''}`)
							}
							command.setPagePrint()
							that.prepareSend(command.getData())
							index++
						}
					}
				} else {
					if (width == 40) {
						width = 50
					}
					if (width == 50) {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(width, height)
						let x = 0;
						let y = 0;
						list.forEach(item => {
							let that = this;
							let t1 = `${item.proId}${item.proColor}${item.proSize}`.length * 50
							let t2 = `${item.remark!=null?item.remark:''}`.length * 60
							let x1 = (width * 10 - t1) / 2
							let x2 = (width * 10 - t2) / 2
							command.setGap(5)
							command.setCls()
							command.setText(x1, y + 30, "TSS24.BF2", firstSize, firstSize,
								`${item.proId}${item.proColor}${item.proSize}`)
							command.setBarCode(70, y + 85, "128", 80, 1, 2, 2, `${item.labelNo}`)
							command.setText(x2, y + 200, "TSS24.BF2", lastSize, lastSize,
								`${item.remark!=null?item.remark:''}`)
							command.setPagePrint()
							that.prepareSend(command.getData())
						})
					}
					if (width == 60) {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(width, height)
						let x = 0;
						let y = 0;
						list.forEach(item => {
							let that = this;
							let t1 = `${item.proId}${item.proColor}${item.proSize}`.length * 50
							let t2 = `${item.remark!=null?item.remark:''}`.length * 60
							let x1 = (width * 10 - t1) / 2
							let x2 = (width * 10 - t2) / 2
							command.setGap(5)
							command.setCls()
							command.setText(x1, y + 30, "TSS24.BF2", firstSize, firstSize,
								`${item.proId}${item.proColor}${item.proSize}`)
							command.setBarCode(25, y + 100, "128", 80, 1, 3, 3, `${item.labelNo}`)
							command.setText(x2, y + 230, "TSS24.BF2", lastSize, lastSize,
								`${item.remark!=null?item.remark:''}`)
							command.setPagePrint()
							that.prepareSend(command.getData())
						})
					}
					if (width == 80) {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(width, height)
						let x = 0;
						let y = 0;
						list.forEach(item => {
							let that = this;
							let t1 = `${item.proId}${item.proColor}${item.proSize}`.length * 50
							let t2 = `${item.remark!=null?item.remark:''}`.length * 60
							let x1 = (width * 10 - t1) / 2 - 10
							let x2 = (width * 10 - t2) / 2 - 20
							command.setGap(5)
							command.setCls()
							command.setText(x1, y + 50, "TSS24.BF2", firstSize, firstSize,
								`${item.proId}${item.proColor}${item.proSize}`)
							command.setBarCode(25, y + 130, "128", 100, 1, 4, 4, `${item.labelNo}`)
							command.setText(x2, y + 330, "TSS24.BF2", lastSize, lastSize,
								`${item.remark!=null?item.remark:''}`)
							command.setPagePrint()
							that.prepareSend(command.getData())
						})
					}
					if (width == 100) {
						let command = tsc.jpPrinter.createNew()
						command.setGap(0)
						command.setCls()
						command.setSize(width, height)
						let x = 0;
						let y = 0;
						list.forEach(item => {
							let that = this;
							let t1 = `${item.proId}${item.proColor}${item.proSize}`.length * 80
							let t2 = `${item.remark!=null?item.remark:''}`.length * 100
							let x1 = (width * 10 - t1) / 2
							let x2 = (width * 10 - t2) / 2
							command.setGap(5)
							command.setCls()
							command.setText(x1, y + 100, "TSS24.BF2", 3, 3,
								`${item.proId}${item.proColor}${item.proSize}`)
							command.setBarCode(25, y + 180, "128", 230, 1, 5, 5, `${item.labelNo}`)
							command.setText(x2, y + 530, "TSS24.BF2", 2, 2,
								`${item.remark!=null?item.remark:''}`)
							command.setPagePrint()
							that.prepareSend(command.getData())
						})
					}
				}
				// #endif
			},


			//准备发送，根据每次发送字节数来处理分包数量1
			prepareSend(buff) {
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},

			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				// console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = app.globalData
				// console.log(BLEInformation)
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						setTimeout(() => {
							currentTime++
							if (currentTime <= loopTime) {
								that.currentTime = currentTime;
								that.Send(buff)
							} else {
								uni.showToast({
									title: '已打印第' + currentPrint + '张',
								})
								if (currentPrint == printNum) {
									that.looptime = 0;
									that.lastData = 0;
									that.currentTime = 1;
									that.isReceiptSend = false;
									that.isLabelSend = false;
									that.currentPrint = 1;
								} else {
									currentPrint++;
									that.currentPrint = currentPrint;
									that.currentTime = 1;
									that.Send(buff)
								}
							}
						}, 10); //就是这里需要加延时，具体原因不清楚
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {

					}
				})
			},

		},
		async onLoad() {
			await this.getList(this.formData)
			let that = this;
			let {
				BLEInformation
			} = app.globalData
		},
		onReady() {
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
				list[j] = i;
				j++
			}
			for (let i = 1; i < 10; i++) {
				numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = app.globalData
		},

	}
</script>
<style lang="scss" scoped>
	::v-deep td {
		font-size: 32rpx;
		position: relative;
		padding: 10rpx 20rpx;
		text-align: center;
		border: 1px solid #999;
	}
</style>
<style lang="scss">
	.toast {
		padding: 16rpx 49rpx;
		border-radius: 29rpx;

		.btn {
			display: flex;
			justify-content: space-around;
			padding: 30rpx 0;

			button {
				width: 463rpx;
				height: 97rpx;
				background: rgba(254, 52, 48, 0);
				border: 3rpx solid #272727;
				border-radius: 49rpx;
				line-height: 97rpx;
			}
		}

		.form {
			border-bottom: 1px solid #f1f1f1;
			padding-bottom: 30rpx;

			.select {
				text-indent: 1em;

				.text {
					margin: 20rpx 0;
					color: #bdbdbd;

					text {
						color: #fe3430;
					}
				}

				input {
					height: 94rpx;
					background: #f2f2f2;
					border-radius: 47rpx;
				}

				.input {
					display: flex;
					align-items: center;
					justify-content: space-between;

					input {
						width: 271rpx;
					}

					text {
						text-align: left;
					}
				}
			}
		}
	}

	.btn1 {
		display: flex;
		padding: 20rpx;

		button {
			height: 58rpx;
			line-height: 58rpx;
			border-radius: 28rpx;
			background-color: #fe3430;
			color: #fff;
			margin: 0 10rpx 0 0;
		}
	}

	.icon-class {
		font-size: 36px;
	}

	.placeholder_class {
		font-size: 16px;
		color: grey;
	}

	.navscroll {
		white-space: nowrap;

	}

	.u-collapse-item {
		font-size: 32rpx;
		white-space: normal;
		word-break: break-all;
		color: #1b253a;
		background-color: #fff;
	}






	.seacchBtn {
		height: 88rpx;
		line-height: 88rpx;
		background: #fe3430;
		border-radius: 49rpx;
		color: #fff;
		margin-left: 20rpx;
		margin-right: 10rpx;
		width: 200rpx;
		font-size: 34rpx;
		text-align: center;
	}
</style>
